package com.mutiplethread.demo;

import com.mutiplethread.demo.service.MyService;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.stream.Stream;

/**
 * 线程通信
 */
public class ThreadComunity {

    private static String Lock = new String();

    public static void main(String[] args) {
        /*MyThread myThread = new MyThread();
        myThread.start();*/
       /* SleepMyThread myThread = new SleepMyThread();
        System.out.println("begin = " + System.currentTimeMillis());
        //同步执行
        // myThread.run();
        //异步执行
        myThread.start();
        System.out.println("end = " + System.currentTimeMillis());*/

        Stream.of("A", "B").forEach(name -> new Thread(ThreadComunity::method2, name).start());
    }

    static void method2() {
       int i = 0;
        synchronized (Lock) {
            try {
                System.out.println("[" + Thread.currentThread().getName() + "] begin wait ...");
                Lock.wait();
                i++;
                System.out.println("[" + Thread.currentThread().getName() + "] end wait ...");
                System.out.println(i);
                if(i==20){
                    Lock.notifyAll();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        int count = 0;
        for (int i = 0; i < 50000000; i++) {
            Thread.yield();
            count = count + (i + 1);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("用时:" + (endTime - beginTime) + "毫秒");
    }
}

class SleepMyThread extends Thread {
    @Override
    public void run() {
        try {
            System.out.println("run threadName=" + this.currentThread().getName() + " begin");
            Thread.sleep(2000);
            System.out.println("run threadName=" + this.currentThread().getName() + " end");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
